//
//  ZqlHTTPClient.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/26.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod:String{
    case GET = "GET"
    case POST = "POST"
}

class ZqlHTTPClient: AFHTTPSessionManager {
    
    let domain = "com.baidu.data.error"
    
    static let sharedClient:ZqlHTTPClient = {
        
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = ZqlHTTPClient(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    func requestJsonDict(method:HTTPMethod,urlString:String,parameters:[String:AnyObject]?,finished:(dict:[String:AnyObject]?,error:NSError?) -> ()){
        if method == .GET{
            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                
                guard let dict = result as? [String:AnyObject] else{
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey : "数据结构出错"])
                    finished(dict: nil, error: myError)
                    return
                }
                //执行成功的回调
                finished(dict: dict, error:nil)
                
                }, failure: { (_, error) -> Void in
                    //执行失败的回调
                    finished(dict: nil, error: error)
            })
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                
                guard let dict = result as? [String:AnyObject] else{
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey : "数据结构出错"])
                    finished(dict: nil, error: myError)
                    return
                }
                //执行成功的回调
                finished(dict: dict, error:nil)
                
                }, failure: { (_, error) -> Void in
                    
                    finished(dict: nil, error: error)
                    
            })
        }
    }
    
}
